package com.slz.crm.server.controller;

import com.slz.crm.common.enumeration.ChartOperates.ChartOperate;
import com.slz.crm.common.exiception.ServiceException;
import com.slz.crm.pojo.dto.DataStatisticsDTO;
import com.slz.crm.server.constant.ChartTitleConstant;
import com.slz.crm.server.service.DataStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/dataStatistics")
@Slf4j
public class DataStatisticsController {
    @Autowired
    private DataStatisticsService dataStatisticsService;

    @PostMapping("/chart")
    @Cacheable(value = "chartCache", key = "#dataStatisticsDTO.title")
    public ResponseEntity<byte[]> generateLineChart(@RequestBody DataStatisticsDTO dataStatisticsDTO) {
        try {
            //分类选择图表
            ChartOperate chartType = (dataStatisticsDTO.getTitle().equals(ChartTitleConstant.COMPANY_SOURCE))
                    ? ChartOperate.PIE_CHART
                    : ChartOperate.LINE_CHART;
            dataStatisticsDTO.setChartType(chartType);
            byte[] chartImage = dataStatisticsService.generateChart(dataStatisticsDTO);

            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "inline; filename=\"chart.jpg\"")
                    .body(chartImage);
        } catch (IOException e) {
            log.info("错误原因：{}", e.getMessage());
            throw new ServiceException("生成图表错误");
        }
    }
}
